<!--
 * @Date: 2022-03-17 16:23:44
 * @Author: 陶子
 * @LastEditTime: 2023-06-25 17:50:19
 * @FilePath: \jk_one-stop_pc\src\views\warehouseManagement\inventoryQuery\buildOutStock.vue
 * @pageName: 这是--(新建仓库)--页面
-->
<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <!--  -->
    <crumbs
      @goBack="goBack"
      :superiorMenu="['仓库管理', '新建仓库']"
      marginBottom="10px"
      currentMenu="新建仓库"
    ></crumbs>
    <div class="form-body">
      <div class="cards-box" >
        <a-card title="基本信息" :bordered="false" style="margin-top: 12px">
          <a-form-model ref="addForm" :model="newAddForm" :rules="addRules" :label-col="labelCol"
                        :wrapper-col="wrapperCol">
            <a-form-model-item label="编号：" prop="applyNumber">
              <a-input v-model="newAddForm.applyNumber" placeholder="请输入" :maxLength="14"
                       @blur="checkInputValue(newAddForm.applyNumber)" />
              <span class="btn-text code-btn" @click="genEntityCode" v-if="!isEdit">自动生成</span>
            </a-form-model-item>
            <a-form-model-item label="仓库名称：" prop="warehouseName">
              <a-input :maxLength="30" v-model="newAddForm.warehouseName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="仓库分类：" prop="warehouseType">
              <a-select placeholder="请选择" v-model="newAddForm.warehouseType" allowClear @change="typeSelectChange">
                <a-select-option :value="undefined">请选择</a-select-option>
                <a-select-option v-for="(item, key) in dictOptions" :key="key" :value="item.value">
              <span :title="item.text || item.label">
                {{ item.text || item.label }}
              </span>
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="仓库管理员：" prop="administerUserCode">
              <j-select-user-by-dep
                @changeRow="userFilter"
                v-model="newAddForm.administerUserCode"
                :limit="5"
                :seldep="true"
                :modalWidth="1000"
                :multi="true"
              ></j-select-user-by-dep>
            </a-form-model-item>
          </a-form-model>
        </a-card>
      </div>
    </div>
    <div class="footer-submit form-footer">
      <!--      <a-button :loading="loadingDraft" @click="submitDraft" style="margin-right: 10px"> 暂存</a-button>-->
      <a-button @click="jkeForm.visible=false" style="margin-right: 10px"> 取消</a-button>
      <a-button type="primary" @click="submitProcess" :loading="submitLoading"> 提交</a-button>
    </div>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import { getNewColumns, subStrText, camelCase2UnderLine, validateDuplicateValue } from '@/utils/util'
import { API } from '@/api/requestFzs'
import { APILX } from '@/api/requestLx'
import { returnMaterialApplyList, getDictModel } from '@/api/goodsManagement'
import { getEnableOne } from '@/api/api'
import axios from 'axios'
import { apiBaseUrl } from '@/utils/request'
import Vue from 'vue'
import { UI_CACHE_DB_DICT_DATA, USER_INFO } from '@/store/mutation-types'

export default {
  components: {
    crumbs
  },
  data() {
    return {
      jkeForm: {
        title: '新建仓库',
        visible: false,
        fullscreen: true,
        switchFullscreen: true
      },
      accloading: false,
      peopleList: [],
      addDialog: false,
      newAddForm: {
        applyNumber: '',
        warehouseName: '',
        warehouseType: '',
        administerUserId: '',
        administerUserCode: ''
      },
      addRules: {
        warehouseName: [{ required: true, message: '请输入', trigger: 'change' }],
        applyNumber: [
          { required: true, message: '请输入', trigger: 'change' }
          // {
          //   message: '该编号已存在',
          //   validator: (rule, value, callback) =>
          //     validateDuplicateValue('WMS_WAREHOUSE', 'apply_number', value, queryId, callback),
          // },
        ],
        warehouseType: [{ required: true, message: '请选择', trigger: 'change' }],
        administerUserCode: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 17 },
      isEdit: false,
      dictOptions: [], //仓库分类字典下拉数据
      validateDuplicateValue, //自动生成编码
      submitLoading: false, // 提交loading
      rules: {
        orderNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        operateTime: [{ required: true, message: '请选择', trigger: 'change' }],
        warehouseId: [{ required: true, message: '请选择', trigger: 'change' }],
        operateTaskType: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      formatParams: {},
      loadingDraft: false,
      modalParams: {},
      clickType: ''
    }
  },
  methods: {
    // 选人
    userFilter(v, row) {
      let uIds = []
      if (row.length > 0) {
        row.forEach((u) => {
          uIds.push(u.id)
        })
        this.newAddForm.administerUserId = uIds.join(',')
      } else {
        this.newAddForm.administerUserId = ''
      }
    },
    initForm(v) {
      this.$store.commit('SET_CURRENT_PREFIX','/jksaas-produce/produce')
      console.log('214324')
      APILX.wmsWarehouseGetTypeList().then((res) => {
        if (res.code == 200) {
          this.dictOptions = res.result
        }
      })
      this.jkeForm.visible = true
    },

    typeSelectChange() {
      //校验一下仓库分类
      this.$refs['addForm'].validateField(['warehouseType'])
    },

    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'WMS_WAREHOUSE' }).then((res) => {
        if (res.code == 200) {
          this.newAddForm.applyNumber = res.result
          this.$refs['addForm'].validateField(['applyNumber'])
        } else {
          this.newAddForm.applyNumber = ''
          this.$refs['addForm'].validateField(['applyNumber'])
          this.$antdMessage.error(res.message)
        }
      })
    },
    checkInputValue(value) {
      validateDuplicateValue('wms_warehouse_operate', 'order_number', value, '', (res) => {
        if (res) {
          this.buildForm.orderNumber = ''
          this.$antdMessage.warning(res)
        }
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    blurNum(e, props, inputKey) {
      let { goodsQualifiedNum, goodsScrapNum, unitPriceExcludingTax } = props.getValue()
      if (goodsQualifiedNum == '0' && goodsScrapNum == '0') {
        this.$antdMessage.warning('输入的合格品数与报废品数之和必须大于0')
      }
      if (goodsQualifiedNum != null && goodsScrapNum != null) {
        let amountExcludingTax = accMul(accAdd(goodsQualifiedNum, goodsScrapNum), unitPriceExcludingTax)
        this.$refs.goodsTable.setValues([
          {
            rowKey: props.rowId, // 行的id
            values: {
              amountExcludingTax: amountExcludingTax.toFixed(2)
            }
          }
        ])
      }
    },

    goBack() {
      this.submitLoading = false
      let fromPage = this.$route.query.fromPage
      if (fromPage == 'stockCheckDetail') {
        let obj = {
          id: this.$route.query.id
        }
        this.$openWay(this, false, '/stockCheckDetail', obj)
      } else {
        let cuttentTab = this.modalParams.cuttentTab
        this.resetCurrentTab(cuttentTab)
        this.jkeForm.visible = false
        this.$emit('refresh', cuttentTab)
      }
    },

    submitProcess(e) {
      if (this.clickType == 'edit') {
        this.saveAction()
      } else {
        console.log(e, 'eeee')
        this.saveAction(e)
      }
    },
    // 点击 modal的取消按钮
    cancelAdd() {
      this.jkeForm.visible = false
      this.$refs['addForm'].resetFields()
    },
    saveAction(processDataVo) {
      this.$refs.addForm.validate((valid) => {
        console.log(valid, 'valid')
        if (valid) {
          this.accloading = true
          let param = this.newAddForm
          param.processDataVo = {}
          console.log('param', param)
          APILX.wmsWarehouseAdd(param)
            .then((res) => {
              if (res.code == 200) {
                this.$antdMessage.success(res.result)
                this.accloading = false
                this.cancelAdd()
              } else {
                this.$antdMessage.error(res.message)
                this.accloading = false
                this.cancelAdd()
              }
            })
            .finally(() => {
              this.accloading = false
              this.cancelAdd()
            })
        }
      })
    },
    submitDraft() {
      // pmDraftSave
      let { values } = this.$refs.goodsTable.getValuesSync({ validate: false })
      let draft = {
        form: this.buildForm,
        editable: values,
        isDraft: true
      }
      this.loadingDraft = true
      pmDraftSave({
        draft,
        entityType: 'BUILD_OUT_STOCK'
      }).then((res) => {
        if (res.code == 200) {
          this.$antdMessage.success(res.message)
          this.goBack()
        } else {
          this.$antdMessage.error(res.message)
        }
        this.loadingDraft = false
      })
    },
    requsetFace() {
      batchStockApi(this.formatParams).then((res) => {
        if (res.success) {
          this.$antdMessage.success(res.message)
          pmDraftDel({ entityType: 'BUILD_OUT_STOCK' }).then((res) => {
          })
          this.goBack()
        } else {
          this.$antdMessage.warning(res.message)
        }
        this.submitLoading = false
      })
    }
  }
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';

/deep/ .ant-card-body{
  padding: 80px;
}
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}

/deep/ .ant-form-vertical {
  display: flex;
  justify-content: space-between;

  .ant-form-item {
    width: 30%;
  }
}

.form-body {
  height: calc(100vh - 188px);
  overflow-y: scroll;
}

.form-footer {
  margin: 12px -12px 0 -12px;
}

.code-btn {
  position: absolute;
  right: 0;
  top: -50px;
  font-size: 14px;
}

.item-wrap {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.item-wrap:nth-of-type(n + 2) {
  margin-top: 40px;
}

.detail-item {
  width: 30%;
}

.bd-line {
  height: 1px;
  background: @greyBorder;
  margin: -12px -40px 24px -40px;
}

.cards-box {
  height: calc(100vh - 188px);
  overflow-y: scroll;
}
</style>
